<?php

/**
 * CelebrioMail MailManagement
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    CelebrioMail
 */
namespace ApplicationsModule\MailModule;

use \Nette\Object;
use \dibi;
use \DibiException;
use \DibiDataSource;

/**
 * Mail Management
 *
 * @author Celebrio Software
 */
class MailManagement extends Object {

    private $mailServerTableName = "celebriomailapp";

    /**
     * Mail Management
     *
     * @author Celebrio Software
     */
    public function __construct() {}

    /**
     * adds or updates a mail server
     * @param MailServer $mailServer
     * @return boolean whether a mail server was created or updated
     */
    public function replaceMailServer(MailServer $mailServer) {
	if ( \is_null($mailServer->getAddress()) ||
	     \is_null($mailServer->getInServer()) ||
	     \is_null($mailServer->getUserid()) ) {
            return false;
        }
        try {
            $res = dibi::fetchSingle("SELECT * FROM [" . $this->mailServerTableName . "] WHERE [user_id]=%i AND [mailaddress]=%s AND [inserver]=%s", $mailServer->getUserid(),$mailServer->getAddress(),$mailServer->getInServer());
            if ($res) {
                $mailServer->setId((int)$res["id"]);
                $mailServer->setCreated($res["created"]);
		dibi::query("UPDATE [" . $this->mailServerTableName . "] SET [mailusername]=%sN,[mailpassword]=%sN,[inprotocol]=%sN,[inport]=%iN,[inssl]=%b,[outserver]=%sN,[outport]=%iN,[outssl]=%b WHERE [id]=%i",
			$mailServer->getUsername(),$mailServer->getPassword(),$mailServer->getInProtocol(),$mailServer->getInPort(),$mailServer->getInSSL(),$mailServer->getOutServer(),$mailServer->getOutPort(),$mailServer->getOutSSL(),$mailServer->getId());
                return true;
            } else {
                dibi::query("INSERT INTO [" . $this->mailServerTableName . "]([user_id],[mailaddress],[mailusername],[mailpassword],[inprotocol],[inserver],[inport],[inssl],[outserver],[outport],[outssl],[sentfolder],[draftsfolder],[trashfolder],[spamfolder]) VALUES
                        (%iN,%sN,%sN,%sN,%sN,%sN,%iN,%b,%sN,%iN,%b,%sN,%sN,%sN,%sN)",
			$mailServer->getUserid(),$mailServer->getAddress(),$mailServer->getUsername(),$mailServer->getPassword(),$mailServer->getInProtocol(),$mailServer->getInServer(),$mailServer->getInPort(),$mailServer->getInSSL(),$mailServer->getOutServer(),$mailServer->getOutPort(),$mailServer->getOutSSL(),$mailServer->getSentFolder(),$mailServer->getDraftsFolder(),$mailServer->getTrashFolder(),$mailServer->getSpamFolder());
                $mailServer->setId(dibi::getInsertId());
                return true;
            }
        } catch (DibiException $e) {
	    // TODO: log the error
            return false;
        }
     }
     
     /**
     * removes a mail server
     * @param MailServer $mailServer
     * @return boolean whether a mail server removed
     */
     public function removeMailServer(MailServer $mailServer) {
	if ( \is_null($mailServer->getId()) ) {
            return false;
        }
	try {
	    dibi::query("DELETE FROM [" . $this->mailServerTableName . "] WHERE [id]=".$mailServer->getId().";");
	    return true;
	} catch (DibiException $e) {
	    // TODO: log the error
            return false;
        }
     }

     /**
      * gets mail servers from a single user
      * @param int $userid
      * @return array of MailServer
      */
     public function getMailServers($userid) {
	$datasource = new DibiDataSource("SELECT * FROM ".$this->mailServerTableName, dibi::getConnection());
	$datasource->where("[user_id]=%i",$userid);
	$datasource->orderBy("mailaddress", Dibi::ASC);
	$result = array ();
	foreach($datasource as $values) {
	    $mailServer = new MailServer(
		$values["user_id"],
		$values["mailusername"],
		$values["mailpassword"],
		$values["mailaddress"],
		$values["inserver"],
		$values["inprotocol"],
		$values["inport"],
		$values["inssl"],
		$values["outserver"],
		$values["outport"],
		$values["outssl"]);
	    $mailServer->setId($values["id"]);
	    $mailServer->setCreated($values["created"]);
	    $mailServer->setSentFolder($values["sentfolder"]);
	    $mailServer->setDraftsFolder($values["draftsfolder"]);
	    $mailServer->setTrashfolder($values["trashfolder"]);
	    $mailServer->setSpamfolder($values["spamfolder"]);
	    $result[]=$mailServer;
	}
	return $result;
     }

}